<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '../stores/cart'
import { useUserStore } from '../stores/user'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 地址表单
const addressForm = ref({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: ''
})

// 选中的地址
const selectedAddress = ref(null)

// 支付方式
const paymentMethod = ref('wechat') // wechat, alipay, card

// 订单备注
const orderRemark = ref('')

// 订单提交状态
const isSubmitting = ref(false)

// 获取选中的购物车商品
const selectedItems = computed(() => {
  return cartStore.items.filter(item => item.selected)
})

// 计算订单总价
const totalPrice = computed(() => {
  return selectedItems.value
    .reduce((total, item) => total + item.price * item.quantity, 0)
    .toFixed(2)
})

// 计算总数量
const totalQuantity = computed(() => {
  return selectedItems.value
    .reduce((total, item) => total + item.quantity, 0)
})

// 配送费（这里模拟固定配送费）
const shippingFee = computed(() => {
  // 订单满99免运费
  return parseFloat(totalPrice.value) >= 99 ? 0 : 10
})

// 实付金额
const finalPrice = computed(() => {
  return (parseFloat(totalPrice.value) + shippingFee.value).toFixed(2)
})

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address
}

// 添加新地址
const addNewAddress = () => {
  // 验证表单
  if (!validateAddressForm()) {
    return
  }
  
  // 创建新地址对象
  const newAddress = {
    id: Date.now().toString(),
    ...addressForm.value
  }
  
  // 保存地址到用户store
  userStore.addAddress(newAddress)
  
  // 选中新添加的地址
  selectedAddress.value = newAddress
  
  // 清空表单
  clearAddressForm()
  
  alert('地址添加成功')
}

// 验证地址表单
const validateAddressForm = () => {
  const { name, phone, province, city, district, detailAddress } = addressForm.value
  
  if (!name.trim()) {
    alert('请输入收件人姓名')
    return false
  }
  
  if (!phone.trim() || !/^1[3-9]\d{9}$/.test(phone)) {
    alert('请输入正确的手机号码')
    return false
  }
  
  if (!province || !city || !district) {
    alert('请选择完整的地区信息')
    return false
  }
  
  if (!detailAddress.trim()) {
    alert('请输入详细地址')
    return false
  }
  
  return true
}

// 清空地址表单
const clearAddressForm = () => {
  addressForm.value = {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: ''
  }
}

// 提交订单
const submitOrder = async () => {
  // 验证是否有选中的地址
  if (!selectedAddress.value) {
    alert('请选择收货地址')
    return
  }
  
  // 验证是否有商品
  if (selectedItems.value.length === 0) {
    alert('请选择要购买的商品')
    router.push('/cart')
    return
  }
  
  try {
    isSubmitting.value = true
    
    // 创建订单对象
    const order = {
      id: Date.now().toString(),
      orderNo: 'ORDER' + Date.now().toString(),
      items: selectedItems.value.map(item => ({
        productId: item.productId,
        name: item.name,
        image: item.image,
        price: item.price,
        quantity: item.quantity,
        spec: item.spec
      })),
      totalPrice: parseFloat(totalPrice.value),
      shippingFee: shippingFee.value,
      finalPrice: parseFloat(finalPrice.value),
      address: selectedAddress.value,
      paymentMethod,
      remark: orderRemark.value,
      status: 'pending', // pending, paid, shipped, delivered, completed
      createdAt: new Date().toISOString()
    }
    
    // 保存订单到用户store
    userStore.addOrder(order)
    
    // 从购物车中移除已购买的商品
    selectedItems.value.forEach(item => {
      cartStore.removeFromCart(item.id)
    })
    
    // 模拟支付成功
    setTimeout(() => {
      alert('订单提交成功！')
      // 跳转到订单详情页或成功页
      router.push('/user/orders')
    }, 1500)
    
  } catch (error) {
    alert('订单提交失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 返回购物车
const backToCart = () => {
  router.push('/cart')
}

// 初始化
onMounted(() => {
  // 检查是否已登录
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 加载用户地址
  if (userStore.addresses.length > 0) {
    selectedAddress.value = userStore.addresses[0]
  }
  
  // 加载购物车数据
  cartStore.loadCart()
})
</script>

<template>
  <main class="checkout-container">
    <div class="container">
      <h1 class="page-title">确认订单</h1>
      
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <span class="breadcrumb-item active">确认订单</span>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-item">支付</span>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-item">完成</span>
      </div>
      
      <div class="checkout-content">
        <!-- 收货地址 -->
        <section class="address-section">
          <h2 class="section-title">收货地址</h2>
          
          <!-- 地址列表 -->
          <div v-if="userStore.addresses.length > 0" class="address-list">
            <div 
              v-for="address in userStore.addresses" 
              :key="address.id"
              class="address-item"
              :class="{ active: selectedAddress && selectedAddress.id === address.id }"
              @click="selectAddress(address)"
            >
              <div class="address-header">
                <span class="recipient-name">{{ address.name }}</span>
                <span class="recipient-phone">{{ address.phone }}</span>
                <span v-if="selectedAddress && selectedAddress.id === address.id" class="selected-tag">已选择</span>
              </div>
              <div class="address-detail">
                {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
              </div>
            </div>
          </div>
          
          <!-- 添加新地址 -->
          <div class="add-address-section">
            <h3 class="add-address-title">添加新地址</h3>
            <div class="address-form">
              <div class="form-row">
                <div class="form-group">
                  <label for="name">收件人</label>
                  <input 
                    type="text" 
                    id="name" 
                    v-model="addressForm.name"
                    placeholder="请输入收件人姓名"
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="phone">手机号码</label>
                  <input 
                    type="tel" 
                    id="phone" 
                    v-model="addressForm.phone"
                    placeholder="请输入手机号码"
                    class="form-input"
                  />
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="province">省份</label>
                  <input 
                    type="text" 
                    id="province" 
                    v-model="addressForm.province"
                    placeholder="请输入省份"
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="city">城市</label>
                  <input 
                    type="text" 
                    id="city" 
                    v-model="addressForm.city"
                    placeholder="请输入城市"
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="district">区县</label>
                  <input 
                    type="text" 
                    id="district" 
                    v-model="addressForm.district"
                    placeholder="请输入区县"
                    class="form-input"
                  />
                </div>
              </div>
              
              <div class="form-group">
                <label for="detailAddress">详细地址</label>
                <textarea 
                  id="detailAddress" 
                  v-model="addressForm.detailAddress"
                  placeholder="请输入详细地址信息"
                  class="form-textarea"
                  rows="3"
                ></textarea>
              </div>
              
              <button class="add-address-btn" @click="addNewAddress">
                添加地址
              </button>
            </div>
          </div>
        </section>
        
        <!-- 商品清单 -->
        <section class="products-section">
          <h2 class="section-title">商品清单</h2>
          <div class="products-list">
            <div 
              v-for="item in selectedItems" 
              :key="item.id" 
              class="order-item"
            >
              <div class="product-info">
                <img :src="item.image" :alt="item.name" class="product-image" />
                <div class="product-details">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-spec" v-if="item.spec">规格：{{ item.spec }}</div>
                </div>
              </div>
              <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="product-quantity">x{{ item.quantity }}</div>
              <div class="product-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
          
          <!-- 订单备注 -->
          <div class="remark-section">
            <label for="remark">订单备注</label>
            <input 
              type="text" 
              id="remark" 
              v-model="orderRemark"
              placeholder="选填，请输入订单备注信息"
              class="remark-input"
            />
          </div>
        </section>
        
        <!-- 支付方式 -->
        <section class="payment-section">
          <h2 class="section-title">支付方式</h2>
          <div class="payment-options">
            <label class="payment-option">
              <input 
                type="radio" 
                name="payment" 
                value="wechat" 
                v-model="paymentMethod"
                class="payment-radio"
              />
              <span class="payment-icon">💚</span>
              <span class="payment-name">微信支付</span>
            </label>
            
            <label class="payment-option">
              <input 
                type="radio" 
                name="payment" 
                value="alipay" 
                v-model="paymentMethod"
                class="payment-radio"
              />
              <span class="payment-icon">💙</span>
              <span class="payment-name">支付宝</span>
            </label>
            
            <label class="payment-option">
              <input 
                type="radio" 
                name="payment" 
                value="card" 
                v-model="paymentMethod"
                class="payment-radio"
              />
              <span class="payment-icon">💳</span>
              <span class="payment-name">银行卡支付</span>
            </label>
          </div>
        </section>
        
        <!-- 订单金额 -->
        <section class="order-summary-section">
          <h2 class="section-title">订单金额</h2>
          <div class="order-summary">
            <div class="summary-item">
              <span class="summary-label">商品总额</span>
              <span class="summary-value">¥{{ totalPrice }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">配送费</span>
              <span class="summary-value">
                {{ shippingFee > 0 ? '¥' + shippingFee.toFixed(2) : '免运费' }}
              </span>
            </div>
            <div class="summary-divider"></div>
            <div class="summary-total">
              <span class="total-label">实付金额</span>
              <span class="total-value">¥{{ finalPrice }}</span>
            </div>
          </div>
        </section>
      </div>
      
      <!-- 提交订单 -->
      <div class="checkout-footer">
        <div class="order-total-info">
          <span class="total-text">共 {{ totalQuantity }} 件商品，合计：</span>
          <span class="total-amount">¥{{ finalPrice }}</span>
        </div>
        <div class="action-buttons">
          <button class="back-cart-btn" @click="backToCart">返回购物车</button>
          <button 
            class="submit-order-btn" 
            @click="submitOrder"
            :disabled="isSubmitting || selectedItems.length === 0 || !selectedAddress"
          >
            <span v-if="!isSubmitting">提交订单</span>
            <span v-else>提交中...</span>
          </button>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
.checkout-container {
  min-height: calc(100vh - 130px);
  padding: 40px 0;
  background-color: #f8f9fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

/* 面包屑导航 */
.breadcrumb {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-bottom: 40px;
  font-size: 16px;
}

.breadcrumb-item {
  color: #666;
}

.breadcrumb-item.active {
  color: #4285f4;
  font-weight: 600;
}

.breadcrumb-separator {
  color: #999;
}

/* 结算内容 */
.checkout-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #4285f4;
}

/* 地址部分 */
.address-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  margin-bottom: 30px;
}

.address-item {
  padding: 20px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.address-item:hover {
  border-color: #4285f4;
}

.address-item.active {
  border-color: #4285f4;
  background-color: rgba(66, 133, 244, 0.05);
}

.address-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.recipient-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.recipient-phone {
  font-size: 14px;
  color: #666;
}

.selected-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #4285f4;
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

/* 地址表单 */
.add-address-section {
  margin-top: 30px;
}

.add-address-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.address-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-input,
.form-textarea {
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4285f4;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.add-address-btn {
  align-self: flex-start;
  padding: 10px 24px;
  background-color: #4285f4;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-address-btn:hover {
  background-color: #3367d6;
}

/* 商品清单 */
.products-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  display: grid;
  grid-template-columns: 1fr 100px 80px 100px;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.product-spec {
  font-size: 14px;
  color: #666;
}

.product-price,
.product-quantity,
.product-subtotal {
  text-align: center;
  font-size: 16px;
}

.product-price {
  color: #666;
}

.product-quantity {
  color: #999;
}

.product-subtotal {
  font-weight: 600;
  color: #333;
}

/* 订单备注 */
.remark-section {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.remark-section label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.remark-input {
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.remark-input:focus {
  outline: none;
  border-color: #4285f4;
}

/* 支付方式 */
.payment-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.payment-options {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px 20px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-option:hover {
  border-color: #4285f4;
}

.payment-radio {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.payment-icon {
  font-size: 24px;
}

.payment-name {
  font-size: 16px;
  color: #333;
}

.payment-option:has(.payment-radio:checked) {
  border-color: #4285f4;
  background-color: rgba(66, 133, 244, 0.05);
}

/* 订单金额 */
.order-summary-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.order-summary {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-label {
  font-size: 16px;
  color: #666;
}

.summary-value {
  font-size: 16px;
  color: #333;
}

.summary-divider {
  height: 1px;
  background-color: #e0e0e0;
  margin: 10px 0;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
}

.total-label {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.total-value {
  font-size: 24px;
  font-weight: 700;
  color: #ff4757;
}

/* 结算底部 */
.checkout-footer {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20px;
  border-top: 2px solid #e0e0e0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
}

.order-total-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-text {
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 24px;
  font-weight: 700;
  color: #ff4757;
}

.action-buttons {
  display: flex;
  gap: 16px;
}

.back-cart-btn {
  padding: 12px 24px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-cart-btn:hover {
  background-color: #e0e0e0;
}

.submit-order-btn {
  padding: 12px 40px;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-order-btn:hover:not(:disabled) {
  background-color: #ff3838;
}

.submit-order-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout-container {
    padding: 20px 0;
  }
  
  .page-title {
    font-size: 28px;
  }
  
  .breadcrumb {
    font-size: 14px;
    gap: 10px;
  }
  
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .order-item {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto;
    gap: 10px;
  }
  
  .product-info {
    grid-column: 1 / -1;
  }
  
  .product-price,
  .product-quantity,
  .product-subtotal {
    text-align: right;
  }
  
  .payment-options {
    flex-direction: column;
    gap: 16px;
  }
  
  .checkout-footer {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .back-cart-btn,
  .submit-order-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .address-section,
  .products-section,
  .payment-section,
  .order-summary-section {
    padding: 20px 15px;
  }
  
  .order-total-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>